import { app, BrowserWindow, shell, ipcMain, Menu } from 'electron'
import fs from 'node:fs'
import path from 'node:path'


/**
 * 等待匹配的数据列表
 */
let list: string[] = []




updateList()
setInterval(() => {
  updateList()
}, 1000 * 30)


/**
 * 更新列表
 */
function updateList() {
  getList().then(l => {
    list = l;
  })
}


/**
 * 获取数据列表
 */
function getList() {
  return new Promise<string[]>((yes) => {
    try {
      const firstPath = path.join(app.getPath('userData'), "userCodeList");
      fs.readFile(firstPath, (err: any, res: any) => {
        if (err) {
          console.log("读取用户列表失败！", err);
          return yes([])
        }
        try {
          yes(JSON.parse(res.toString('utf8')))
        } catch (error) {
          console.log("解析用户列表文件失败！", error);
          yes([])
        }
      })
    } catch (error) {
      yes([])
    }
  })
}



/**
 * 相似度算法函数
 */
function levenshteinDistance(a: string, b: string, maxDistance: number) {
  const lenA = a.length, lenB = b.length;
  if (Math.abs(lenA - lenB) > maxDistance) return maxDistance + 1;
  if (lenA === 0) return lenB;
  if (lenB === 0) return lenA;
  let prevRow = [], currentRow = [];
  for (let i = 0; i <= lenB; i++) prevRow[i] = i;
  for (let i = 1; i <= lenA; i++) {
    currentRow[0] = i;
    let minDistance = currentRow[0];
    for (let j = 1; j <= lenB; j++) {
      let insertOrDelete = Math.min(currentRow[j - 1] + 1, prevRow[j] + 1);
      let replace = prevRow[j - 1];
      if (a[i - 1] !== b[j - 1]) replace++;
      currentRow[j] = Math.min(insertOrDelete, replace);
      if (currentRow[j] < minDistance) minDistance = currentRow[j];
    }
    if (minDistance > maxDistance) return maxDistance + 1;
    [prevRow, currentRow] = [currentRow, prevRow];
  }
  return prevRow[lenB];
}



/**
 * 相识度比对，返回相识度最高的数据
 * @param b 要进行比对的字符
 * @returns  最终的数据
 */
export function getStrFamiliarity(b: string): {
  closestItem: string,
  similarityPercent: number,
} {
  let minDistance = Infinity;
  let closestItem = null;
  let similarityPercent = 0;

  for (const item of list) {
    if (
      item
      && b
      && item == b
    ) {
      return {
        closestItem: item,
        similarityPercent: 100,
      }
    }
    const distance = levenshteinDistance(item, b, minDistance);
    if (distance < minDistance) {
      minDistance = distance;
      closestItem = item;
    }
  }

  if (closestItem !== null) {
    const maxLength = Math.max(closestItem.length, b.length);
    similarityPercent = (1 - minDistance / maxLength) * 100;
  }

  return {
    closestItem: closestItem,
    similarityPercent: Number(similarityPercent.toFixed(2))
  };
}
